#!/usr/bin/env python3
"""
快速测试LLM推理数据与MCP模型集成
用于快速验证单个异常场景的处理流程
"""

import json
import requests
from datetime import datetime

# 配置
MCP_BASE_URL = "http://localhost:8085"

def generate_test_anomaly_data():
    """生成测试用的异常数据"""
    return {
        "timestamp": datetime.now().isoformat(),
        "server_id": "kylin-test-server",
        "anomaly_score": 0.82,
        "confidence": 0.89,
        "anomaly_type": "cpu_overload",
        "severity": 7.5,
        "affected_components": ["cpu", "system"],
        "anomaly_details": {
            "cpu_usage": {
                "current": 98.5,
                "threshold": 85.0,
                "trend": "increasing",
                "duration": "1h"
            },
            "load_average": {
                "current": 15.2,
                "threshold": 8.0,
                "cores": 8
            }
        },
        "root_cause_analysis": {
            "primary_cause": "high_cpu_intensive_process",
            "secondary_causes": ["insufficient_resources", "memory_leak"],
            "impact_scope": "system_performance",
            "estimated_resolution_time": "20m"
        },
        "recommended_actions": [
            {
                "action_type": "immediate",
                "description": "识别并终止高CPU进程",
                "priority": "critical",
                "estimated_time": "5m"
            },
            {
                "action_type": "short_term",
                "description": "优化系统资源配置",
                "priority": "high",
                "estimated_time": "15m"
            }
        ],
        "context": {
            "business_impact": "系统响应缓慢",
            "affected_users": 500,
            "peak_hours": True,
            "maintenance_window": False
        }
    }

def test_llm_inference_processing():
    """测试LLM推理数据处理"""
    print("🔍 测试LLM推理数据处理...")
    
    # 生成测试数据
    test_data = generate_test_anomaly_data()
    print(f"异常类型: {test_data['anomaly_type']}")
    print(f"严重程度: {test_data['severity']}")
    print(f"异常分数: {test_data['anomaly_score']}")
    
    try:
        # 将测试数据包装在llm_data字段中
        request_data = {"llm_data": test_data}
        response = requests.post(
            f"{MCP_BASE_URL}/api/intelligent/process_llm_inference",
            json=request_data,
            headers={'Content-Type': 'application/json'},
            timeout=30
        )
        
        if response.status_code == 200:
            result = response.json()
            print("✅ LLM推理数据处理成功")
            
            # 从响应中提取计划ID
            if result.get('success') and result.get('result'):
                plan_data = json.loads(result['result'][0]['text'])
                plan_id = plan_data.get('plan_id')
                print(f"计划ID: {plan_id}")
                print(f"问题类型: {plan_data.get('problem_type')}")
                print(f"风险等级: {plan_data.get('risk_level')}")
                print(f"任务数量: {plan_data.get('tasks_count')}")
                print(f"响应详情: {json.dumps(result, indent=2, ensure_ascii=False)}")
                return plan_id
            else:
                print(f"响应详情: {json.dumps(result, indent=2, ensure_ascii=False)}")
                return None
        else:
            print(f"❌ LLM推理数据处理失败: {response.status_code}")
            print(f"错误信息: {response.text}")
            return None
            
    except Exception as e:
        print(f"❌ LLM推理数据处理异常: {e}")
        return None

def test_decision_execution(decision_id):
    """测试决策执行"""
    if not decision_id:
        print("❌ 没有有效的决策ID，跳过决策执行测试")
        return
    
    print(f"\n🚀 测试决策执行...")
    print(f"决策ID: {decision_id}")
    
    try:
        response = requests.post(
            f"{MCP_BASE_URL}/api/intelligent/execute_decision/{decision_id}",
            timeout=30
        )
        
        if response.status_code == 200:
            result = response.json()
            print("✅ 决策执行成功")
            print(f"执行状态: {result.get('status')}")
            print(f"响应详情: {json.dumps(result, indent=2, ensure_ascii=False)}")
        else:
            print(f"❌ 决策执行失败: {response.status_code}")
            print(f"错误信息: {response.text}")
            
    except Exception as e:
        print(f"❌ 决策执行异常: {e}")

def test_script_generation(decision_id):
    """测试脚本生成"""
    if not decision_id:
        print("❌ 没有有效的决策ID，跳过脚本生成测试")
        return
    
    print(f"\n📝 测试Ansible脚本生成...")
    
    try:
        response = requests.post(
            f"{MCP_BASE_URL}/api/ansible/generate-script/{decision_id}",
            timeout=30
        )
        
        if response.status_code == 200:
            result = response.json()
            print("✅ Ansible脚本生成成功")
            print(f"脚本ID: {result.get('script_id')}")
            print(f"脚本类型: {result.get('script_type')}")
            print(f"响应详情: {json.dumps(result, indent=2, ensure_ascii=False)}")
            return result.get('script_id')
        else:
            print(f"❌ Ansible脚本生成失败: {response.status_code}")
            print(f"错误信息: {response.text}")
            return None
            
    except Exception as e:
        print(f"❌ Ansible脚本生成异常: {e}")
        return None

def test_script_deployment(script_id):
    """测试脚本部署"""
    if not script_id:
        print("❌ 没有有效的脚本ID，跳过脚本部署测试")
        return
    
    print(f"\n🚀 测试脚本部署到Kylin服务器...")
    
    try:
        response = requests.post(
            f"{MCP_BASE_URL}/api/ansible/deploy-script/{script_id}",
            timeout=30
        )
        
        if response.status_code == 200:
            result = response.json()
            print("✅ 脚本部署成功")
            print(f"部署状态: {result.get('status')}")
            print(f"目标服务器: {result.get('target_server')}")
            print(f"响应详情: {json.dumps(result, indent=2, ensure_ascii=False)}")
        else:
            print(f"❌ 脚本部署失败: {response.status_code}")
            print(f"错误信息: {response.text}")
            
    except Exception as e:
        print(f"❌ 脚本部署异常: {e}")

def test_health_check():
    """测试系统健康状态"""
    print("🏥 检查MCP系统健康状态...")
    
    try:
        response = requests.get(f"{MCP_BASE_URL}/api/health", timeout=10)
        if response.status_code == 200:
            print("✅ MCP系统健康检查通过")
            return True
        else:
            print(f"❌ MCP系统健康检查失败: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ 无法连接到MCP系统: {e}")
        return False

def main():
    """主函数"""
    print("🧪 MCP模型LLM推理数据快速测试")
    print("=" * 50)
    
    # 1. 健康检查
    if not test_health_check():
        print("❌ 系统健康检查失败，停止测试")
        return
    
    # 2. 测试LLM推理数据处理
    decision_id = test_llm_inference_processing()
    
    # 3. 测试决策执行
    test_decision_execution(decision_id)
    
    # 4. 测试脚本生成
    script_id = test_script_generation(decision_id)
    
    # 5. 测试脚本部署
    test_script_deployment(script_id)
    
    print("\n" + "=" * 50)
    print("✅ 快速测试完成")
    print("=" * 50)

if __name__ == "__main__":
    main() 